//
//  DetailOrderViewController.m
//  GoBigMarket
//
//  Created by 李真 on 16/8/22.
//  Copyright © 2016年 legend. All rights reserved.
//  订单详情页面

#import "DetailOrderViewController.h"
#import "DetailOrderCell.h"
#import "DetailFooterView.h"
#import "DetailOrderModel.h"
#import "OrdersProductModel.h"
#import "Order.h"
#import "BeeCloud.h"
#import "CommodityViewController.h"
#import <AlipaySDK/AlipaySDK.h>
@interface DetailOrderViewController ()<BeeCloudDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *topImageView;//
@property (weak, nonatomic) IBOutlet UITableView *tableView;//
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;//

@property (weak, nonatomic) IBOutlet UIView *bottomView;//底部视图
@property (weak, nonatomic) IBOutlet UILabel *zhifuType;//支付方式

@property (weak, nonatomic) IBOutlet UILabel *dingdanhaoLabel;//订单号
@property (weak, nonatomic) IBOutlet UILabel *lianxirenLabel;//联系人
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;//电话
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;//地址
@property (weak, nonatomic) IBOutlet UILabel *timeLable;//时间
@property (weak, nonatomic) IBOutlet UIButton *enterBtn;

@property (nonatomic,strong)UIButton *headerBtn;//tableView的顶部btn
@property (nonatomic,strong)DetailFooterView *footerView;//tableView的底部视图

@property (nonatomic,strong)UIImageView *arrowsImage;//箭头指示器

@property (nonatomic,strong)NSMutableDictionary *dataDic;//页面底部 数据字典
@property (nonatomic,strong)NSMutableArray *dataList;//商品页面数据

@property (nonatomic,strong)DetailOrderModel *detailModel;//页面model
@property (nonatomic,strong)OrdersProductModel *producModel;//产品model
@property (nonatomic, strong) NSMutableString *encodeStr;
@end

@implementation DetailOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"订单详情";
//    [self addData];
    
    
}
#pragma mark - 生命周期
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    [BeeCloud setBeeCloudDelegate:self];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear: animated];
    
}
#pragma mark - 网络请求
-(void)setOrderId:(NSString *)orderId{
    if (_orderId != orderId) {
        _orderId = orderId;
    }
    
    if (!self.dataList) {
        self.dataList = [NSMutableArray array];
    }
    
    NSDictionary *par = @{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":_orderId} ;
    self.detailModel = [[DetailOrderModel alloc]init];
    
    [CQNetWorkTools GETWithURL:GetOrderDetail par:par success:^(id                                                                                                                                            responseObject) {
        DLog(@"订单详情: %@",responseObject);
        if ([[responseObject valueForKey:@"Err"]integerValue] != 0) {
            //失败
           [SVProgressHUD  showWithStatus:[responseObject objectForKey:@"ErrMsg"]];
        }else{
            
            self.detailModel = [DetailOrderModel mj_objectWithKeyValues:[responseObject valueForKey:@"Order"]];
            [self addData];

            self.dataList = [OrdersProductModel mj_objectArrayWithKeyValuesArray:self.detailModel.Products];
            
            if (self.dataList.count > 1) {
                _arrowsImage.hidden = NO;
            }
            
            [self.tableView reloadData];
        }
    } filed:^(NSError *error) {
        DLog(@"订单详情 error %@",error);
    }];
}
//加载数据
- (void)addData{
    /**
     
     {
     Address = "\U5730\U5740\U957f\U957f\U5730\U5740702";
     CellPhone = 13498765432;
     Coupon = "0.00";
     Id = 2016083018449317;
     OrderDate = "2016-08-30";
     OrderStatus = 4;
     OrderTotalAmount = "0.02";
     PaymentTypeName = "";
     ProductCount = 1;
     Products =         (
     {
     );
     ShipTo = mao;
     YunFei = 0;
     };
     }
  
     */
    
    self.dingdanhaoLabel.text = [NSString stringWithFormat:@"订单号：%@",self.detailModel.Id];
    self.addressLabel.text = [NSString stringWithFormat:@"收货地址：%@",self.detailModel.Address];//收货地址
    
    self.phoneLabel.text = [NSString stringWithFormat:@"联系电话：%@",self.detailModel.CellPhone];//收货电话
    self.timeLable.text = [NSString stringWithFormat:@"下单时间：%@",self.detailModel.OrderDate];
    self.zhifuType.text = [NSString stringWithFormat:@"支付方式: %@",self.detailModel.PaymentTypeName];
    self.footerView.hejiLabel.text = [NSString stringWithFormat: @"%@元",self.detailModel.OrderTotalAmount];//实付价格
    self.footerView.youHuiLabel.text = [NSString stringWithFormat:@"%@元",self.detailModel.Coupon];
//    self.footerView.countNum.text = [NSString stringWithFormat:@"共%@件",self.detailModel.ProductCount];
    [_headerBtn setTitle:self.detailModel.ShopName forState:UIControlStateNormal];
    self.lianxirenLabel.text = [NSString stringWithFormat:@"联系人：%@",self.detailModel.ShipTo];//联系人
    /**
     *  订单状态，1待付款,2待发货,3待收货,4已关闭,5已完成,7未评价。这里返回数字用于判断订单环节状态
     */
    NSString *imageName = [NSString stringWithFormat:@"dingdanxiqngqing-%d",self.detailModel.OrderStatus];
    self.topImageView.image = [UIImage imageNamed:imageName];
    
}
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    //获取当前小组的状态，根据isClose判断是展开是还是收起
    BOOL isClose = _close[section];
    
    if (!isClose) {//是YES的话收起，返回1个单元格
        tableView.height = 140 + 120;
        
        return 1;
    }
    //如果不是YES，就展开，返回相对应的小组的单元格数量
    tableView.height = 140 * self.dataList.count + 120;
    
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DetailOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dOrderCell"];
    if (!cell) {
        cell = [[[NSBundle mainBundle]loadNibNamed:@"DetailOrderCell" owner:self options:nil]lastObject];
    }
    if (self.dataList.count > 0) {
        cell.model = self.dataList[indexPath.row];
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 140;
}

//组footerView
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (!_footerView) {
        _footerView = [[[NSBundle mainBundle]loadNibNamed:@"DetailFooterView" owner:nil options:nil]lastObject];
    }
    return self.footerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 80;
}
//按钮点击事件
- (void)btnAction:(UIButton *)btn{
    
    //改变这个小组的展开或者收起状态
    _close[0] = !_close[0];
    //刷新表视图
    [self.tableView reloadData];
    [self viewDidLayoutSubviews];
}

#pragma mark- cell点击
//点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    DetailOrderCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    CommodityViewController *productVC = [[CommodityViewController alloc]init];
    productVC.ProductId =  [NSString stringWithFormat:@"%d",cell.model.ProductId];
    [self.navigationController pushViewController:productVC animated:YES];
}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    
    
    /**
     *  订单状态，1待付款,2待发货,3待收货,4已关闭,5已完成,7未评价。这里返回数字用于判断订单环节状态
     */
    
    //enterBtn 有两种状态 一个是 确定 一个去支付
    if (self.state == 1) {
        [self.enterBtn setTitle:@"去支付" forState:0];
        [self.enterBtn addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
    }
//    else if (self.state == 3){
//        [self.enterBtn setTitle:@"确认收货" forState:0];
//        [self.enterBtn addTarget:self action:@selector(enterBtn) forControlEvents:UIControlEventTouchUpInside];
//    }
    else{
        [self.enterBtn setTitle:@"确定" forState:0];
        [self.enterBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    BOOL isClose = _close[0];

    if (!_headerBtn) {
        _headerBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _headerBtn.frame = CGRectMake(0, 0, XNWindowWidth, 40);
        _headerBtn.backgroundColor = [UIColor whiteColor];
        _headerBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
        [_headerBtn setTitle:@"商店名称" forState:UIControlStateNormal];
        //居左显示
        _headerBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        _headerBtn.titleEdgeInsets = UIEdgeInsetsMake(0,15, 0, 0);
//        _headerBtn.hidden = YES;
        [_headerBtn setTitleColor:[UIColor blackColor] forState:0];
        [_headerBtn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        self.tableView.tableHeaderView = _headerBtn;
    }
    if (!_arrowsImage) {
        _arrowsImage = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"下拉箭头黑色"]];
        _arrowsImage.hidden = YES;
        _arrowsImage.frame = CGRectMake(XNWindowWidth - 50, 15, 15, 10);
        [_headerBtn addSubview:_arrowsImage];
    }
    if (!isClose) {//是YES的话收起，返回1个单元格
        _tableView.height = 140 + 120;
        _arrowsImage.image = [UIImage imageNamed:@"下拉箭头黑色"];
        
    }else{
        //如果不是YES，就展开，返回相对应的小组的单元格数量
        //    NSArray *arr = _data[section];
        _tableView.height = 140 * self.dataList.count + 120;
        _arrowsImage.image = [UIImage imageNamed:@"矩形-3-拷贝-11"];
    }
    
    _bottomView.top = self.tableView.bottom + 2;
    self.scrollView.contentSize = CGSizeMake(XNWindowWidth, _bottomView.bottom + 5);
}
#pragma mark - pop
- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 确认收货
- (void)enterProduct{
    DLog(@"确认收货");
}
#pragma mark - 支付
- (void)payAction{
    DLog(@"支付");
//    [self goCount];
    [self pullAlert];
}

#pragma mark - 选择支付方式
- (void)pullAlert {
    UIAlertController *sheetController = [UIAlertController alertControllerWithTitle:@"请选择支付方式" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"支付宝支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self goCount];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"微信支付" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self beeCloudPayOrder];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        DLog(@"取消");
    }];
#warning Cancel按钮一直在最下边，并且上拉菜单类型不可以添加文本框
    [sheetController addAction:action1];
    [sheetController addAction:action2];
    [sheetController addAction:action3];
    [self presentViewController:sheetController animated:YES completion:^{
        
    }];
}
#pragma mark - beeCloud 微信去支付
- (void)beeCloudPayOrder {
    [CQNetWorkTools POSTWithURL:beeCloudSubmitOrder par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.orderId,@"PlatType": @"IOS"} success:^(id responseObject) {
        NSString *BillNum =[responseObject objectForKey:@"BillNum"];
        NSString *BillTitle =[responseObject objectForKey:@"BillTitle"];
        NSString *BillTotalFee =[responseObject objectForKey:@"BillTotalFee"];
        NSString *PayId = [responseObject objectForKey:@"PayId"];
        [self doPay:PayChannelWxApp BillNum:BillNum BillTitle:BillTitle BillTotalFee:BillTotalFee PayId:PayId];
    } filed:^(NSError *error) {
        
    }];
}
#pragma mark - beeCloud支付
- (void)doPay:(PayChannel)channel BillNum:(NSString *)BillNum BillTitle:(NSString *)BillTitle BillTotalFee:(NSString *)BillTotalFee PayId:(NSString *)PayId{
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value",@"key", nil];
    /**
     按住键盘上的option键，点击参数名称，可以查看参数说明
     **/
    BCPayReq *payReq = [[BCPayReq alloc] init];
    /**
     *  支付渠道，PayChannelWxApp,PayChannelAliApp,PayChannelUnApp,PayChannelBaiduApp
     */
    payReq.channel = channel; //支付渠道
    payReq.title = BillTitle;//订单标题
    payReq.totalFee = [NSString stringWithFormat:@"%@", BillTotalFee];//订单价格; channel为BC_APP的时候最小值为100，即1元
    payReq.billNo = [NSString stringWithFormat:@"%@", BillNum];//商户自定义订单号
    
    payReq.scheme = @"wxdeaf20c134765733";//URL Scheme,在Info.plist中配置; 支付宝必有参数
    payReq.billTimeOut = 300;//订单超时时间
    payReq.viewController = self; //银联支付和Sandbox环境必填
    payReq.cardType = 0; //0 表示不区分卡类型；1 表示只支持借记卡；2 表示支持信用卡；默认为0
    payReq.optional = dict;//商户业务扩展参数，会在webhook回调时返回
    [BeeCloud sendBCReq:payReq];
}


- (void)goCount {
    self.encodeStr = [NSMutableString string];
    
    [CQNetWorkTools POSTWithURL:ShopCartGoPay par:@{@"ShouJiHao":GETPHONE,@"Token":GETTOKEN,@"Duuid":GETUUID,@"OrderId":self.orderId,@"PlatType": @"IOS"} success:^(id responseObject) {
        DLog(@"去结算成功%@", [responseObject objectForKey:@"Parm"]);
        NSString *parm = [responseObject objectForKey:@"Parm"];
        NSArray *array = [parm componentsSeparatedByString:@"&"];
        DLog(@"%@", array);
        Order* order = [Order new];
        // NOTE: 商品数据
        order.biz_content = [BizContent new];
        for (int i =0 ; i < array.count; i++) {
            NSString *str = [array objectAtIndex:i];
            NSArray *arr = [str componentsSeparatedByString:@"="];
            NSString *string = [NSString string];
            if (arr.count == 3) {
                string = [[arr objectAtIndex:1]  stringByAppendingString:@"="];
            }else {
                string = [arr lastObject];
            }
            NSString *key = [arr firstObject];
            switch (i) {
                case 0:{
                    // NOTE: app_id设置
                    order.app_id = string;
                    DLog(@"软件号码%@", self.encodeStr);
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.app_id]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 1:{
                    DLog(@"方法%@", self.encodeStr);
                    // NOTE: 支付接口名称
                    order.method = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.method]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 2:{
                    DLog(@"方式%@", self.encodeStr);
                    order.charset = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.charset]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 3:{
                    DLog(@"加签格式%@", self.encodeStr);
                    // NOTE: 参数编码格式
                    order.sign_type = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.sign_type]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 4:{
                    DLog(@"时间%@", self.encodeStr);
                    // NOTE: 当前时间点
                    order.timestamp = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.timestamp]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 5:{
                    // NOTE: 支付版本
                    order.version = string;
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.version]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 6:
                {
                    order.notify_url = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.notify_url]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 7:{
                    // NOTE: sign_type设置
                    order.biz = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.biz]stringByAppendingString:@"&"].mutableCopy;
                }
                    break;
                case 8:{
                    order.sign = (__bridge_transfer  NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 );
                    self.encodeStr = [[[[self.encodeStr stringByAppendingString:key]stringByAppendingString:@"="]stringByAppendingString:order.sign]stringByAppendingString:@"="].mutableCopy;
                }
                    break;
                default:
                    break;
            }
        }
        DLog(@"最后字符串%@", self.encodeStr);
        NSString *appScheme = @"chen";
        // NOTE: 调用支付结果开始支付
        [[AlipaySDK defaultService] payOrder:self.encodeStr
                                  fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                                      DLog(@"reslut = %@",resultDic);
                                      if ([[responseObject valueForKey:@"resultStatus"]integerValue] == 9000) {
                                          //发通知刷新订单列表
//                                          [[NSNotificationCenter defaultCenter]postNotificationName:@"QuXiaoDingDan" object:nil];
                                      }
                                  }];
    } filed:^(NSError *error) {
        DLog(@"去结算失败%@", error);
    }];
}
#pragma mark - 微信支付回调
- (void)onBeeCloudResp:(BCBaseResp *)resp {
    
    switch (resp.type) {
        case BCObjsTypePayResp:
        {
            
            // 支付请求响应
            BCPayResp *tempResp = (BCPayResp *)resp;
            if (tempResp.resultCode == 0) {
                BCPayReq *payReq = (BCPayReq *)resp.request;
                //百度钱包比较特殊需要用户用获取到的orderInfo，调用百度钱包SDK发起支付
                if (payReq.channel == PayChannelBaiduApp && ![BeeCloud getCurrentMode]) {
                    
                } else {
                    //微信、支付宝、银联支付成功
                    self.tabBarController.selectedIndex = 0;
                }
            } else {
                //支付取消或者支付失败
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryBillsResp:
        {
            
            BCQueryBillsResp *tempResp = (BCQueryBillsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [self showAlertView:@"未找到相关订单信息"];
                } else {
                    
                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        case BCObjsTypeQueryRefundsResp:
        {
            
            BCQueryRefundsResp *tempResp = (BCQueryRefundsResp *)resp;
            if (resp.resultCode == 0) {
                if (tempResp.count == 0) {
                    [self showAlertView:@"未找到相关订单信息"];
                } else {
                    
                    [self performSegueWithIdentifier:@"queryResult" sender:self];
                }
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",tempResp.resultMsg, tempResp.errDetail]];
            }
        }
            break;
        default:
        {
            if (resp.resultCode == 0) {
                [self showAlertView:resp.resultMsg];
            } else {
                [self showAlertView:[NSString stringWithFormat:@"%@ : %@",resp.resultMsg, resp.errDetail]];
            }
        }
            break;
    }
}
- (void)showAlertView:(NSString *)msg {
    UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    [alert show];
}

@end
